# -*- coding: utf-8 -*-
import logging

import simplejson
import werkzeug.utils
from odoo import http
from odoo.addons.auth_oauth.controllers.main import OAuthController as Controller
from odoo.addons.auth_oauth.controllers.main import OAuthLogin as Home
from odoo.http import request
from werkzeug.exceptions import BadRequest
from werkzeug.urls import url_encode

_logger = logging.getLogger(__name__)


class OAuthLogin(Home):
    def list_providers(self):
        # 获取所有的OAuth服务商
        providers = super(OAuthLogin, self).list_providers()
        for provider in providers:
            # provider['auth_endpoint']获取的就是身份验证网址
            # 服务商的相关字段信息可以在数据库结构中搜索模型auth就可以找到了
            if 'weixin' in provider['auth_endpoint']:
                # 你的微信APPID
                APPID = request.env['ir.config_parameter'].sudo().get_param('odoo_wechat_login.appid')

                # 构造微信请求参数
                params = dict(
                    response_type='code',
                    appid=APPID,
                    # 微信回调处理url，后面的wechat是我自己添加的，可改，但要与下面的路径一致
                    redirect_uri=request.httprequest.url_root + 'wechat/login',
                    scope=provider['scope'],
                    # 我这里把服务商id放在这个参数中
                    state=provider['id']  
                )
                # 最终的微信登入请求链接
                provider['auth_link'] = "%s?%s" % (
                    provider['auth_endpoint'],
                    url_encode(params)
                )
        return providers


class OAuthController(Controller):
    # 此处的路径'/wechat/login'与上面所填的redirect_uri要一致
    @http.route('/wechat/login', type='http', auth='none')
    def wechat_login(self, **kw):
        dbname = request.session.db
        if not http.db_filter([dbname]):
            return BadRequest()
        state = kw.get('state', '')
        # 取出OAuth服务商
        provider = int(state)

        code = kw.get('code', '')
        if not code:
            return BadRequest()

        wechat_providers = request.env['auth.oauth.provider'].sudo().search([('id', '=', provider)])
        
        # 拼接请求参数
        state = {
            "d": dbname,
            "p": provider,
        }
        params = {
            'expires_in': 7200,
            'access_token': code,
            'scope': wechat_providers.scope,
            'token_type': 'Bearer'
        }
        params['state'] = simplejson.dumps(state)
        return werkzeug.utils.redirect('/auth_oauth/signin?%s' % url_encode(params))